package cn.lishiyuan.algorithm.bit;


import java.nio.charset.StandardCharsets;

/**
 * 布隆过滤器
 */
public class BloomFilter {
    private final BitMap map;
    private long count;

    public BloomFilter(int size) {
        this.map= new BitMap(size);
        this.count = 0;
    }

    public boolean contains(String word) {
        return contains(word.getBytes(StandardCharsets.UTF_8));
    }

    public boolean contains(byte[] word) {
        long murIndex = MurmurHash.hash64(word);
        // 防止出现负数
        murIndex = Math.abs(murIndex);
        long metIndex = MetroHash.hash64(word);
        // 防止出现负数
        metIndex = Math.abs(metIndex);
        return map.getBoolean(murIndex) && map.getBoolean(metIndex);
    }

    public void put(String word) {
        put(word.getBytes(StandardCharsets.UTF_8));
    }

    public void put(byte[] word) {
        // 防止出现负数
        long murIndex = MurmurHash.hash64(word);
        murIndex = Math.abs(murIndex);
        long metIndex = MetroHash.hash64(word);
        metIndex = Math.abs(metIndex);

        map.set(murIndex);
        map.set(metIndex);
        count++;
    }

    public long getCount(){
        return count;
    }

}
